<template>
  <div>
    <div class="">
      <el-button type="primary" @click="add">添加任务</el-button>
      <el-button
        type="primary"
        :disabled="!multipleSelection.length"
        @click="executeAll"
        >执行已选中</el-button
      >
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="list"
      border
      style="width: 100%; margin-top: 15px"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="任务名"></el-table-column>
      <el-table-column prop="dir" label="项目根目录"></el-table-column>
      <el-table-column prop="buildCommond" label="打包命令"></el-table-column>
      <el-table-column prop="otherCommond" label="后执行命令"></el-table-column>
      <!-- <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{ statusList?.[scope.row.status] || "" }}
        </template>
      </el-table-column> -->
      <el-table-column label="服务器配置" width="400">
        <template #default="scope">
          <div style="max-height: 100px; overflow: auto">
            <div v-for="(value, key) in scope.row">{{ key }}: {{ value }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button link type="primary" @click="edit(scope.row)">
            编辑</el-button
          >
          <!-- <el-button link type="primary" @click="updateStatus(scope.row)"> 待执行</el-button> -->
          <el-button link type="primary" @click="del(scope.row)">
            删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form label-position="top" :model="formData" :rules="rules" ref="formRef">
        <div v-if="formStatus === 0">
          <h1>任务设置</h1>
          <el-form-item label="任务名" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="项目根目录" prop="dir">
            <el-input v-model="formData.dir"></el-input>
          </el-form-item>
          <el-form-item label="打包命令" prop="buildCommond">
            <el-input v-model="formData.buildCommond"></el-input>
          </el-form-item>
          <el-form-item label="后执行命令">
            <el-input v-model="formData.otherCommond" placeholder="打包后需要执行的其他操作,示例: node -v"></el-input>
          </el-form-item>
          <el-form-item label="打包文件目录" prop="localPath">
            <el-input v-model="formData.localPath" placeholder="打包后的静态资源相对项目根目录地址, 示例: dist"></el-input>
          </el-form-item>
        </div>
        <div v-if="formStatus === 1">
          <h1>服务器配置</h1>
          <el-text type="danger">如果省略, 将使用默认服务器配置中的属性</el-text>
          <el-form-item label="服务器地址" prop="host">
            <el-input v-model="formData.host"></el-input>
          </el-form-item>
          <el-form-item label="port" prop="port">
            <el-input v-model="formData.port"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password"></el-input>
          </el-form-item>
          <el-form-item label="远程路径" prop="remotePath">
            <el-input v-model="formData.remotePath"></el-input>
          </el-form-item>
          <el-form-item label="远程备份路径" prop="remoteBackupPath">
            <el-input v-model="formData.remoteBackupPath"></el-input>
          </el-form-item>
          <el-form-item label="远程服务器命令" prop="remoteCommand">
            <el-input v-model="formData.remoteCommand"></el-input>
          </el-form-item>
          <el-form-item label="备份数量" prop="backMaxNum">
            <el-input v-model="formData.backMaxNum" type="number" placeholder="不小于1的整数"></el-input>
          </el-form-item>
          <!-- <el-form-item label="备注"> 
              <el-input v-model="formData.remark"></el-input>
          </el-form-item> -->
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="formStatus === 0" @click="formStatusClick"
            >下一步</el-button
          >
          <el-button v-if="formStatus === 1" @click="formStatus = 0"
            >上一步</el-button
          >
          <el-button v-if="formStatus === 1" type="primary" @click="change">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
// 全部执行
const executeAll = () => {
  ElMessageBox.confirm("确认全部执行任务吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      try {
        window.pywebview.api.startJob(
          multipleSelection.value.map((item) => item.id)
        );
        ElMessage.success("操作成功, 执行过程中请勿重复点击此按钮");
        init();
      } catch (error) {
        ElMessage.error(error.message);
      }
    })
    .catch(() => {});
};

const dialogVisible = ref(false);
const dialogTitle = ref("");
const formStatus = ref(0);
const list = ref([]);
const formData = ref({});
const statusList = ref(["无", "待执行", "执行中等待中", "执行中", "执行完成"]);
// 编辑操作
const edit = (item) => {
  dialogTitle.value = "编辑任务";
  formData.value = JSON.parse(JSON.stringify(item));
  formStatus.value = 0;
  dialogVisible.value = true;
};
const emit = defineEmits(["updateConfig"]);
// 获取任务列表
const init = async () => {
  const result = await window.pywebview.api.getJobList();
  if (result.code === 200) {
    list.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};
init();

// setInterval(() => {
//   init()
// }, 1000);
// 添加操作
const add = async () => {
  dialogTitle.value = "添加任务";
  formStatus.value = 0;
  formData.value = {
    name: "",
    dir: "",
    buildCommond: "",
    otherCommond: "",
    localPath: "dist",
    host: "",
    port: "",
    username: "",
    password: "",
    remotePath: "",
    remoteBackupPath: "",
    remoteCommand:"",
    backMaxNum: "",
  };
  dialogVisible.value = true;
};
// 删除操作
const del = async (item) => {
  ElMessageBox.confirm("确认删除吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      try {
        const result = await window.pywebview.api.delJob(item.id);
        if (result.code === 200) {
          ElMessage.success("删除成功");
          init();
        } else {
          ElMessage.error(result.msg);
        }
      } catch (error) {
        ElMessage.error(error);
      }
    })
    .catch(() => {});
};
const formRef = ref(null);
// 弹窗确认按钮
const change = async () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogTitle.value === "添加任务") {
          const result = await window.pywebview.api.addJob(formData.value);
          if(result.code === 200) {
            ElMessage.success("添加成功");
          }else {
            ElMessage.error(result.msg);
          }
        } else {
          const result = await window.pywebview.api.updateJob(formData.value);
          if(result.code === 200) {
            ElMessage.success("修改成功");
          }else {
            ElMessage.error(result.msg);
          }
        }
        dialogVisible.value = false;
        init();
      } catch (error) {
        ElMessage.error(error.message);
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
};
// 下一步操作
const formStatusClick = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      formStatus.value = 1
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const rules = reactive({
  name: [{ required: true, message: "请输入任务名", trigger: "blur" }],
  dir: [{ required: true, message: "请输入项目根目录", trigger: "blur" }],
  buildCommond: [{ required: true, message: "请输入打包命令", trigger: "blur" }],
  localPath: [{ required: true, message: "请输入打包文件目录", trigger: "blur" }],
  // host: [{ required: true, message: "请输入服务器地址", trigger: "blur" }],
  // port: [{ required: true, message: "请输入端口", trigger: "blur" }],
  // username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  // password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  // remotePath: [{ required: true, message: "请输入远程路径", trigger: "blur" }],
  // remoteBackupPath: [
  //   { required: true, message: "请输入远程备份路径", trigger: "blur" },
  // ],
  backMaxNum: [
    {
      required: false,
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (!value) {
          // callback(new Error("请输入备份数量"));
          callback()
        } else if (!/^[1-9]\d*$/.test(value)) {
          callback(new Error("请输入不小于1的整数"));
        } else {
          callback();
        }
      },
    },
  ],
});
// 将方法暴露给父组件
defineExpose({
  init,
});
</script>

